/*
 * Projet industriel VAMP 2012 
 */
package com.vampmobile.android.activity;

import java.util.ArrayList;
import java.util.List;

import com.vampmobile.R;
import com.vampmobile.android.VampApplication;
import com.vampmobile.android.VampCommon.Commons.KINDS;
import com.vampmobile.android.db.VampDatabase;
import com.vampmobile.android.db.VampDatabase.VampDBHelper;
import com.vampmobile.android.tools.ActivityParameters;
import com.vampmobile.android.tools.ApplicationMenu;
import com.vampmobile.android.tools.ImageLoader;
import com.vampmobile.android.tools.ImageLoader.ImageCallback;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AlphabetIndexer;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ResourceCursorAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

/**
 * class to display POI FO && AM
 */
public class Poi extends Activity implements ListView.OnScrollListener,
		ListView.OnItemClickListener {
	public static final String TAG = "POI";

	private ListView mListView;
	private ItemAdapter mAdapter;
	public static VampDBHelper mDbHelper;
	private Cursor mCursor;
	private boolean mLoaded = false;
	private boolean mBusy = false;
	private ImageView mHomeTitle;
	private ImageButton mHomeButton;
	private ImageView mHomeVoice;
	private ImageButton mBackButton;
	private ImageButton mSearchButton;
	private ImageView mSearchText;
	private ImageView mAddPoi;
	private TextView mSearchInput;
	private ImageButton mQuitButton;
	private ImageButton mAccountButton;
	private int mfavoris;
    private static final int REQUEST_CODE = 1234;    
	/*
	 * method used by clicking on the list of item
	 */
	class ItemClickListener implements OnClickListener {

		private String name = null;
		private Long id = null;
		private KINDS kind = null;

		public ItemClickListener(KINDS kind) {
			super();
			this.kind = kind;
		}

		// case video and music
		public ItemClickListener(KINDS kind, Long id, String name) {
			super();
			this.kind = kind;
			this.id = id;
			this.name = name;
		}

		public void onClick(View mView) {
			switch (kind) {
			case ADD:
				goNew();
				break;
			case POI:
				goPoiDetail(id);
				break;
			case TOOLBAR:
				FrameLayout toolbar1 = (FrameLayout) findViewById(R.id.toolbar);
				if (toolbar1.getVisibility() != View.VISIBLE)
					toolbar1.setVisibility(View.VISIBLE);
				else
					toolbar1.setVisibility(View.GONE);
				break;
			case QUIT:
				android.os.Process.killProcess(android.os.Process.myPid());
				java.lang.System.exit(0);
				finish();
				break;
			case SEARCH:
				FrameLayout toolbar2 = (FrameLayout) findViewById(R.id.toolbar);
				toolbar2.setVisibility(View.GONE);
				mSearchInput.requestFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
		        imm.showSoftInput(mSearchInput, 0); 
				break;
			case SEARCH_TEXT:
				ArrayList<String> lst = new ArrayList<String>();
				lst.add(mSearchInput.getText().toString());
				goSearch(lst);
				break;
			case VOICE:
				startVoiceRecognitionActivity();
				break;
			case BACK:
				String txt = mSearchInput.getText().toString();
				if (txt!=null && 
					txt.trim().length()>0) {
					mSearchInput.setText(null);
					updatelistView(null);
				} else {
					if (ActivityParameters.themetId == null)
						goHome();
					else
						goThemes();
				}
				break;
			case PROFILE_TITLE:
				goProfile();
				break;
			case HOME_TITLE:
				goHome();
				break;
			}

		}
	}

	/**
	 * Called when the activity is first created. Responsible for initializing
	 * the UI.
	 */
	@Override
	public void onCreate(Bundle icicle) {
		Log.i(TAG, "est OK");
		super.onCreate(icicle);
		setTitle(TAG);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.poi_list);
		String title = (ActivityParameters.themeName != null) ? ActivityParameters.themeName
				: TAG;
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		((TextView) findViewById(R.id.activityTitle)).setText(title);
		// button of title bar
		mHomeTitle = (ImageView) findViewById(R.id.home_title);
		mHomeTitle.setOnClickListener(new ItemClickListener(KINDS.TOOLBAR));
		// button of toolbar
		mHomeButton = (ImageButton) findViewById(R.id.home);
		mHomeButton.setOnClickListener(new ItemClickListener(KINDS.HOME_TITLE));
		mBackButton = (ImageButton) findViewById(R.id.back_button);
		mBackButton.setOnClickListener(new ItemClickListener(KINDS.BACK));
		mSearchButton = (ImageButton) findViewById(R.id.search);
		mSearchButton.setOnClickListener(new ItemClickListener(KINDS.SEARCH));
		mQuitButton = (ImageButton) findViewById(R.id.quit);
		mQuitButton.setOnClickListener(new ItemClickListener(KINDS.QUIT));
		mAccountButton = (ImageButton) findViewById(R.id.account);
		mAccountButton.setOnClickListener(new ItemClickListener(
				KINDS.PROFILE_TITLE));
		mAddPoi = (ImageView) findViewById(R.id.button_poi_add);
		mAddPoi.setOnClickListener(new ItemClickListener(
				KINDS.ADD));
		mSearchText = (ImageView) findViewById(R.id.button_poi_search);
		mSearchText.setOnClickListener(new ItemClickListener(
				KINDS.SEARCH_TEXT));
		mSearchInput = (TextView) findViewById(R.id.text_search);
		mHomeVoice = (ImageView) findViewById(R.id.home_voice);
		PackageManager pm = getPackageManager();        
		List<ResolveInfo> activities = pm.queryIntentActivities(                
				new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);        
		if (activities.size() == 0) {            
			mHomeVoice.setEnabled(false);            
			Toast.makeText(getApplicationContext(),
					"Voice recognizer not present!..", Toast.LENGTH_LONG).show();
		} else {
			mHomeVoice.setOnClickListener(new ItemClickListener(KINDS.VOICE));
		}
		updatelistView(null);

	}

	private void updatelistView(ArrayList<String> lst) {
		if (mCursor != null) {
			mCursor.close();
		}

		// Cursor for Adapter
		mDbHelper = VampDatabase.getInstance(this).getDbHelper();
		if (lst==null) {
			lst = new ArrayList<String>();
			lst.add(mSearchInput.getText().toString());
		}
		mCursor = mDbHelper.getPoiByTheme(ActivityParameters.themetId, lst);
		// Adapter
		mAdapter = new ItemAdapter(Poi.this, R.layout.poi_row, mCursor);
		mListView = (ListView) findViewById(R.id.poi_list);
		mListView.setAdapter(mAdapter);
		mListView.setOnScrollListener(this);
		mListView.setOnItemClickListener(this);
		mListView.setFastScrollEnabled(true);
		startManagingCursor(mCursor);
		ListView poilst = (ListView) findViewById(R.id.poi_list);
		poilst.invalidateViews();
	}
    /**     * Fire an intent to start the voice recognition activity.     */    
	protected void startVoiceRecognitionActivity() {        
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);        
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,                
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);        
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");        
		startActivityForResult(intent, REQUEST_CODE);    
		}     
	/**     * Handle the results from the voice recognition activity.     */    
	@Override    
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {        
		if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {            
			// Populate the wordsList with the String values the recognition engine thought it heard            
			ArrayList<String> matches = data.getStringArrayListExtra(                    
					RecognizerIntent.EXTRA_RESULTS);  
			goSearch(matches);
		}        
		super.onActivityResult(requestCode, resultCode, data);    
	}

	@Override
	public void onResume() {
		super.onResume();
		onNewIntent(getIntent());
	}

	@Override
	public void finish() {
		if (mCursor != null) {
			mCursor.close();
			mCursor = null;
		}
		if (mDbHelper != null) {
			mDbHelper.close();
			mDbHelper = null;
		}
		super.finish();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
	}

	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		mCursor.moveToPosition(position);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		ApplicationMenu.onCreateOptionsMenu(this, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		ApplicationMenu.onPrepareOptionsMenu(this, menu);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		ApplicationMenu.onOptionsItemSelected(this, item);
		return true;
	}

	private class ItemAdapter extends ResourceCursorAdapter implements
			SectionIndexer {
		private final AlphabetIndexer mAlphaIndexer;
		private final Bitmap mDefaultImage;
		private final ImageLoader mImageLoader;

		public ItemAdapter(Context context, int layout, Cursor cursor) {
			super(context, layout, cursor, true);
			if (cursor != null)
				mAlphaIndexer = new AlphabetIndexer(cursor,
						cursor.getColumnIndex(VampDatabase.POI_TITLE_COL),
						"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ");
			else
				mAlphaIndexer = null;
			mImageLoader = VampApplication.getInstance().getImageLoader();
			mDefaultImage = BitmapFactory.decodeResource(getResources(),
					R.drawable.star);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			final View view = super.newView(context, cursor, parent);
			final ViewCache cache = new ViewCache();
			cache.title = (TextView) view.findViewById(R.id.poi_title);
			cache.adress1 = (TextView) view.findViewById(R.id.poi_address1);
			cache.adress2 = (TextView) view.findViewById(R.id.poi_address2);
			cache.adress3 = (TextView) view.findViewById(R.id.poi_zipcode_town);
			cache.thumbnail = (ImageView) view.findViewById(R.id.poi_img);
			// img favoris
			cache.mImgFavoris = (ImageView) view.findViewById(R.id.poi_star_fovoris);
			cache.mImgFavorisOn = (ImageView) view.findViewById(R.id.poi_star_fovoris_on);
			view.setTag(cache);

			return view;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ViewCache cache = (ViewCache) view.getTag();
			cache.id = cursor.getLong(cursor
					.getColumnIndex(VampDatabase.BASE_ID_COL));
			cache.title.setText(cursor.getString(cursor
					.getColumnIndex(VampDatabase.POI_TITLE_COL)));
			cache.adress1.setText(cursor.getString(cursor
					.getColumnIndex(VampDatabase.POI_LINE1_COL)));
			cache.adress2.setText(cursor.getString(cursor
					.getColumnIndex(VampDatabase.POI_LINE2_COL)));
			cache.adress3.setText(cursor.getString(cursor
					.getColumnIndex(VampDatabase.POI_ZIPCODE_COL))
					+ " "
					+ cursor.getString(cursor
							.getColumnIndex(VampDatabase.POI_CITY_COL)));

			// onClick icon favoris =========================================
			mfavoris = mCursor.getInt(mCursor
					.getColumnIndex(VampDatabase.POI_FAVORITE_COL));
			if (mfavoris == 1) {
				cache.mImgFavoris.setVisibility(View.GONE);
				cache.mImgFavorisOn.setVisibility(View.VISIBLE);
			} else {
				cache.mImgFavoris.setVisibility(View.VISIBLE);
				cache.mImgFavorisOn.setVisibility(View.GONE);
			}

			view.setOnClickListener(new ItemClickListener(KINDS.POI, cache.id,
					cache.title.getText().toString()));

			cache.thumbnail.setImageBitmap(mDefaultImage);
			// Image si existe
			cache.pendingThumbnailUrl = null;
			String imgURL = cursor.getString(cursor
					.getColumnIndex(VampDatabase.POI_IMGURL_COL));
			cache.pendingThumbnailUrl = imgURL;
			cache.lazyPending = false;

			if (!TextUtils.isEmpty(cache.pendingThumbnailUrl)) {

				if (!mBusy
						|| mImageLoader
								.isImageLoaded(cache.pendingThumbnailUrl)) {
					setViewThumbnail(view, cache);
				} else {
					cache.thumbnail.setImageBitmap(mDefaultImage);
					cache.thumbnail.setTag(cache.pendingThumbnailUrl);

					cache.lazyPending = true;
				}
			} else {
				cache.thumbnail.setImageBitmap(mDefaultImage);
			}
		}

		public void setViewThumbnail(View view, final ViewCache cache) {
			cache.lazyPending = false;

			Bitmap cached = mImageLoader.loadImage(cache.pendingThumbnailUrl,
					new ImageCallback() {
						public void onSuccess(String url, Bitmap image) {
							if (cache.pendingThumbnailUrl == url) {
								cache.thumbnail.setTag(null);
								cache.thumbnail.setImageBitmap(image);
							}
						}

						public void onFailure(String url) {
							Log.w(TAG, "Loading Failed: " + url);
						}
					});

			if (cached == null) {
				cached = mDefaultImage;
			}
			cache.thumbnail.setImageBitmap(cached);
		}

		public void lazyBindViews() {
			ListView view = mListView;
			int first = view.getFirstVisiblePosition();
			int count = view.getChildCount();

			for (int i = 0; i < count; i++) {
				View child = view.getChildAt(i);
				ViewCache cache = (ViewCache) child.getTag();

				if (cache != null && cache.lazyPending) {
					setViewThumbnail(view, cache);
				}
			}
		}

		private class ViewCache {
			public boolean lazyPending = true;
			public String pendingThumbnailUrl;
			public ImageView thumbnail;
			public TextView title;
			public TextView adress1;
			public TextView adress2;
			public TextView adress3;
			public Long id;
			public ImageView mImgFavoris;
			public ImageView mImgFavorisOn;
		}

		public int getPositionForSection(int section) {
			return mAlphaIndexer.getPositionForSection(section); // use the
			// indexer
		}

		public int getSectionForPosition(int position) {
			return mAlphaIndexer.getSectionForPosition(position); // use the
			// indexer
		}

		public java.lang.Object[] getSections() {
			return mAlphaIndexer.getSections(); // use the indexer
		}

	}

	public void goPoiDetail(Long poiId) {
		ActivityParameters.poiId = poiId;
		Intent myIntent = new Intent();
		myIntent.setClass(getApplicationContext(), PoiDetail.class);
		myIntent.setAction(Intent.ACTION_VIEW);
		myIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		finish();
		startActivity(myIntent);

	}

	public void goProfile() {
		ActivityParameters.themetId = null;
		ActivityParameters.themeName = null;
		Intent myIntent = new Intent();
		myIntent.setClass(getApplicationContext(), Profile.class);
		myIntent.setAction(Intent.ACTION_VIEW);
		finish();
		startActivity(myIntent);
	}

	public void goHome() {
		ActivityParameters.themetId = null;
		ActivityParameters.themeName = null;
		ActivityParameters.poiId=null;
		Intent i = new Intent();
		i.setClass(getApplicationContext(), Home.class);
		i.setAction(Intent.ACTION_VIEW);
		finish();
		startActivity(i);
	}

	public void goNew() {
		ActivityParameters.themetId = null;
		ActivityParameters.themeName = null;
		ActivityParameters.poiId=null;
		Intent i = new Intent();
		i.setClass(getApplicationContext(), PoiNew.class);
		i.setAction(Intent.ACTION_VIEW);
		finish();
		startActivity(i);
	}

	public void goThemes() {
		ActivityParameters.themetId = null;
		ActivityParameters.themeName = null;
		ActivityParameters.poiId=null;
		Intent i = new Intent();
		i.setClass(getApplicationContext(), Theme.class);
		i.setAction(Intent.ACTION_VIEW);
		finish();
		startActivity(i);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			String txt = mSearchInput.getText().toString();
			if (txt!=null && 
					txt.trim().length()>0) {
					mSearchInput.setText(null);
					updatelistView(null);
			} else {
				if (ActivityParameters.themetId == null)
					goHome();
				else
					goThemes();
			}
			return true;
		}
		return false;
	}

	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

	}

	public void onScrollStateChanged(AbsListView view, int scrollState) {
		switch (scrollState) {
		case OnScrollListener.SCROLL_STATE_IDLE:
			mBusy = false;
			mAdapter.lazyBindViews();
			break;
		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
		case OnScrollListener.SCROLL_STATE_FLING:
			mBusy = true;
			break;
		}

	}
	public void goSearch(ArrayList<String> lstWords) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(mSearchInput.getWindowToken(), 0);
		Long count = mDbHelper.getPoiCountByTheme(ActivityParameters.themetId, lstWords);
		if (count==1) {
			goPoiDetail(mDbHelper.getPoiSingleResultByTheme(ActivityParameters.themetId, lstWords));
		} else {
			updatelistView(lstWords);
		}
	}

}
